<template>
  <el-dialog
    v-model="show"
    title="分配角色"
    width="30%"
    :before-close="handleClose"
  >
    <el-select
      v-model="selectedRoleIds"
      multiple
      placeholder="Select"
      style="width: 240px"
    >
      <el-option
        v-for="item in options"
        :key="item.value"
        :label="item.label"
        :value="item.value"
      />
    </el-select>
    <template #footer>
      <span class="dialog-footer">
        <el-button>取消</el-button>
        <el-button type="primary" @click="sureFn"> 确定 </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { user } from "@/api";
import { computed, reactive, ref, toRefs, watch } from "vue";

const props = defineProps({
  show: {
    type: Boolean,
    default: false,
  },
  data: {
    type: Number,
    default: 0,
  },
});

const handleClose = () => {
  emit("hide");
  // 把数据清空
  selectedRoleIds.value = [];
};

const selectedRoleIds = ref<number[]>([]);

interface IState {
  rollList: IRoleModel[];
}
const state = reactive<IState>({
  rollList: [],
});

user.getRoleListApi().then((res) => {
  if (res.code === 200) {
    state.rollList = res.data;
  }
});

const options = computed(() => {
  return state.rollList.map((item) => ({
    // vlaue 是 下拉的 选项的真实值 -- 一般是id之类
    value: item.id,
    // label 是 下拉 选项的 显示的内容 -- 目前我们要显示的是 角色的名称
    label: item.name,
  }));
});

const emit = defineEmits(["hide"]);

watch(
  () => props.data,
  () => {
    if (props.data === 0) return;
    // 向服务器发请求，得到传入的id对应的用户的所有的角色
    user.getRoleListByAdminIdApi(props.data).then((res) => {
      if (res.code === 200) {
        selectedRoleIds.value = res.data.map((item) => item.id);
      }
    });
  }
);

const sureFn = () => {
  // 把修改后的数据，向服务器同步
  user.updateRolesApi({
    adminId: props.data,
    roleIds: selectedRoleIds.value,
  });
};
</script>

<style scoped></style>
